package br.uneb.tebd.local;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import br.uneb.tebd.R;
import br.uneb.tebd.model.Guitar;
import br.uneb.tebd.model.GuitarRepository;

public class CreateLocalGuitar extends Activity {
	
	private Button register;
	private TextView description;
	private TextView model;
	private TextView brand;
	
	private GuitarRepository guitarRepository;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.new_guitar);
		
		this.guitarRepository = new GuitarRepository(this);
		
		this.register = (Button) findViewById(R.id.registerButton);
		
		this.description = (TextView) findViewById(R.id.description);
		
		this.model = (TextView) findViewById(R.id.model);
		
		this.brand = (TextView) findViewById(R.id.brand);
		
		this.register.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				//Salvando guitarra.
				if (haveAnyBlankField() == false) {
					Guitar guitar = new Guitar();
					
					guitar.setModel(model.getText().toString().trim());
					guitar.setDescription(description.getText().toString().trim());
					guitar.setBrand(brand.getText().toString().trim());
					
					Guitar guitarFromDb = guitarRepository.findGuitarByDescription(guitar.getDescription());
					
					if (guitarFromDb == null) {
						guitarRepository.save(guitar);
						
						Toast.makeText(CreateLocalGuitar.this, "Guitarra registrada com sucesso.", Toast.LENGTH_SHORT).show();
						clearFields();
					} else {
						Toast.makeText(CreateLocalGuitar.this, "Essa guitarra ja foi registrada.", Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
	}
	
	private void clearFields() {
		this.description.setText("");
		this.model.setText("");
		this.brand.setText("");
	}
	
	private boolean haveAnyBlankField() {
		
		boolean result = false;
		String description = this.description.getText().toString().trim();
		
		if (description.equals("")) {
			Toast.makeText(this, "E preciso preencher todos os campos.", Toast.LENGTH_SHORT).show();
			result = true;
		}
		
		String model = this.model.getText().toString().trim();
		
		if (model.equals("")) {
			Toast.makeText(this, "E preciso preencher todos os campos.", Toast.LENGTH_SHORT).show();
			result = true;
		}
		
		String brand = this.brand.getText().toString().trim();
		
		if (brand.equals("")) {
			Toast.makeText(this, "E preciso preencher todos os campos.", Toast.LENGTH_SHORT).show();
			result = true;
		}
		
		return result;
	}
}
